package com.xuchaotong.zk.utils;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author 311633
 * @version 1.0
 * @ClassName:
 * @Description:
 * @date 2018/1/31 15:05
 */
public class ZookeeperUtils {
    private static final String connectionInfo = "10.230.34.217:2181,10.230.34.217:2182,10.230.34.217:2183";
    private static ZookeeperUtils instance = null;
    private static CuratorFramework client = null;
    private static Object lock = new Object();


    private ZookeeperUtils() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString(connectionInfo)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();

        client.start();
    }

    public static ZookeeperUtils getInstance(){
        if(instance == null){
            synchronized (lock){
                instance = new ZookeeperUtils();
                return instance;
            }
        }

        return instance;
    }

    public void createNode(String path,String val){
        try {
            client.create().creatingParentContainersIfNeeded().forPath(path,val.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteNode(String node){
        try {
            if(!node.startsWith("/")){
                node = "/" + node;
            }
            client.delete().forPath(node);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateNode(String path,String val){
        try {
            client.setData().forPath(path,val.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
